goog.provide('mitel.socket');

goog.require('goog.events');
goog.require('goog.json');
goog.require('goog.net.WebSocket');
goog.require('goog.net.WebSocket.EventType');
goog.require('goog.net.XhrIo');
goog.require('mitel.deployment');



/**
 * @constructor
 */
mitel.socket.Socket = function(serverurl) {
  var _socket = new goog.net.WebSocket();
  this.socket = _socket;

  var ts = (new Date()).getTime();
  goog.net.XhrIo.send(serverurl + 'socket.io/1/?t=' + ts, function(e) {
    var xhr = e.target;
    var obj = xhr.getResponseText();
    var values = obj.split(':');

    var ws = serverurl.replace('https', 'wss');
    var ws = ws.replace('http', 'ws');

    _socket.open(ws + 'socket.io/1/websocket/' + values[0]);
  });
};


/**
 * @return {mitel.socket.Socket} A socket wrapper matching Socket.IO interface.
 * @param {string} eventtype The event type to listen for.
 * @param {Function} callback Callback function on message.
 */
mitel.socket.Socket.prototype.on = function(eventtype, callback) {
  if (eventtype == 'connect') {
    this._connect(callback);
    return;
  }

  goog.events.listen(this.socket,
      goog.net.WebSocket.EventType.MESSAGE,
      function(event) {
        var message = event['message'];

        if (!goog.string.startsWith(message, '5:::')) {
          return;
        }

        var json_serialized = goog.string.remove(message, '5:::');
        var obj = goog.json.parse(json_serialized);

        if (obj['name'] != eventtype) {
          return;
        }

        callback(obj['args'][0]);
      });
};


mitel.socket.Socket.prototype.emit = function(eventtype, data) {
  var args = {
    'name': eventtype,
    'args': [data]
  };
  this.socket.send('5:::' + goog.json.serialize(args));
};


mitel.socket.Socket.prototype._connect = function(callback) {
  goog.events.listen(this.socket, goog.net.WebSocket.EventType.OPENED, callback);
};

mitel.socket.Socket.prototype._event = function(eventtype, event, callback) {

};

mitel.socket.connect = function(serverurl) {
  var socket = io.connect(serverurl);
  return socket;
};
